//
//  UserCenterViewController.m
//  SportSocial
//
//  Created by yull on 15/1/12.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "UserCenterViewController.h"
#import "FriendBasicCell.h"
#import "FriendHobbyCell.h"
#import "SportPlanNet.h"
#import "UIScrollView+PullToRefresh.h"
#import "NDRefreshLoadMoreContainView.h"

static NSDateFormatter *dateFormatter = nil;

@interface UserCenterViewController () <UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UserModel *userInfo;

@property (nonatomic, strong) UITableView *centerTableView;

@property (nonatomic, strong) NSMutableArray *sportHistoryArray;;

@property (nonatomic, assign) NSUInteger currentPage;
@property (nonatomic, assign) NSUInteger totalPage;

@end

@implementation UserCenterViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.centerTableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    self.centerTableView.backgroundColor = [UIColor clearColor];
    self.centerTableView.dataSource = self;
    self.centerTableView.delegate = self;
    self.centerTableView.tableFooterView = [[UIView alloc] init];
    self.centerTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.centerTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.centerTableView];
    
    self.currentPage = 0;
    
    @weakify(self)
    [self.centerTableView nd_addPullToLoadMoreWithActionHandler:^(id sender) {
        @strongify(self)
        [self loadSportHistory];
    }];
}

- (void)setTopView:(UIView *)topView
{
    topView.top = 0;
    
    self.centerTableView.tableHeaderView = topView;
}

- (void)removeTopView
{
    if (self.centerTableView.tableHeaderView) {
        self.centerTableView.tableHeaderView = nil;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return section == 0 ? 5:self.sportHistoryArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 30.0f;
        }else if (indexPath.row == 1) {
            return [FriendBasicCell calculateCellHeightWithUser:self.userInfo];
        }else if (indexPath.row == 2 || indexPath.row == 4) {
            return 40.0f;
        }else if (indexPath.row == 3) {
            return 60.0f;
        }
    }
    return 30.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0 || indexPath.row == 2 || indexPath.row == 4) {
            static NSString *titleIdentifier = @"TitleCell";
            UITableViewCell *titleCell = [tableView dequeueReusableCellWithIdentifier:titleIdentifier];
            if (!titleCell) {
                titleCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:titleIdentifier];
                titleCell.selectionStyle = UITableViewCellSelectionStyleNone;
                titleCell.textLabel.font = [UIFont boldSystemFontOfSize:15.0f];
                titleCell.textLabel.textColor = [UIColor blackColor];
                
                CGRect rect = CGRectMake(10, titleCell.contentView.height - 1.0f, titleCell.contentView.width-10, 1.0f);
                UIView *lineView = [[UIView alloc] initWithFrame:rect];
                lineView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleTopMargin;
                lineView.backgroundColor = RGB(240, 242, 242);
                [titleCell.contentView addSubview:lineView];
            }
            
            titleCell.textLabel.top = indexPath.row == 0 ? 10 : 30;
            titleCell.textLabel.left = 10;
            if (indexPath.row == 0) {
                titleCell.textLabel.text = @"基本信息";
            }else if (indexPath.row == 2) {
                titleCell.textLabel.text = @"运动爱好";
            }else {
                titleCell.textLabel.text = @"锻炼历程";
            }
            
            return titleCell;
        }else if (indexPath.row == 1) {
            static NSString *basicIdentifier = @"BasicCell";
            FriendBasicCell *basicCell = [tableView dequeueReusableCellWithIdentifier:basicIdentifier];
            if (!basicCell) {
                basicCell = [[FriendBasicCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:basicIdentifier];
                
                CGRect rect = CGRectMake(10, basicCell.contentView.height - 1.0f, basicCell.contentView.width-10, 1.0f);
                UIView *lineView = [[UIView alloc] initWithFrame:rect];
                lineView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleTopMargin;
                lineView.backgroundColor = RGB(240, 242, 242);
                [basicCell.contentView addSubview:lineView];

            }
            [basicCell drawCellWithUserModel:self.userInfo];
            return basicCell;
        }else if (indexPath.row == 3) {
            
            FriendHobbyCell *hobbyCell = [tableView dequeueReusableCellWithIdentifier:@"HobbyCell"];
            if (!hobbyCell) {
                hobbyCell = [[FriendHobbyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HobbyCell"];
                
                CGRect rect = CGRectMake(10, hobbyCell.contentView.height - 1.0f, hobbyCell.contentView.width-10, 1.0f);
                UIView *lineView = [[UIView alloc] initWithFrame:rect];
                lineView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleTopMargin;
                lineView.backgroundColor = RGB(240, 242, 242);
                [hobbyCell.contentView addSubview:lineView];
            }
            
            [hobbyCell drawCellWithUserModel:self.userInfo];
            return hobbyCell;
        }
    }else {
        UITableViewCell *planCell = [tableView dequeueReusableCellWithIdentifier:@"PlanCell"];
        if (!planCell) {
            planCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"PlanCell"];
            planCell.selectionStyle = UITableViewCellSelectionStyleNone;
            planCell.textLabel.font = [UIFont systemFontOfSize:13.0f];
            planCell.textLabel.textColor = RGB(169, 169, 169);
        }
        
        dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        
        NSDictionary *sportDic = [self.sportHistoryArray objectAtIndex:indexPath.row];
        
        NSMutableString *sportStr = [NSMutableString string];
        
        if ([[sportDic objectForKey:@"start_date"] length]) {
            NSString *start_date = [sportDic objectForKey:@"start_date"];
            
            [sportStr appendFormat:@"%@  ", [start_date substringToIndex:10]];
        }
        
        if ([[sportDic objectForKey:@"sport_name"] length]) {
            
            [sportStr appendFormat:@"%@  ", [sportDic objectForKey:@"sport_name"]];
        }
        
        if ([[sportDic objectForKey:@"end_date"] length] &&
            [[sportDic objectForKey:@"start_date"] length]) {
            
            NSString *end_date = [sportDic objectForKey:@"end_date"];
            NSString *start_date = [sportDic objectForKey:@"start_date"];
            
            NSDate *endDate = [dateFormatter dateFromString:end_date];
            NSDate *startDate = [dateFormatter dateFromString:start_date];
            
            NSTimeInterval duration = [endDate timeIntervalSince1970] - [startDate timeIntervalSince1970];
            
            NSString *timeStr = nil;
            if (duration >= 3600) {
                timeStr = [NSString stringWithFormat:@"%ld时%ld分%ld秒", ((NSInteger)duration / 3600), ((NSInteger)duration%3600) / 60, ((NSInteger)duration%60)];
            } else if (duration >= 60 && duration < 3600) {
                timeStr = [NSString stringWithFormat:@"%ld分%ld秒", ((NSInteger)duration%3600) / 60, ((NSInteger)duration%60)];
            } else {
                timeStr = [NSString stringWithFormat:@"%ld秒", ((NSInteger)duration%60)];
            }
            
            [sportStr appendString:timeStr];
        }
        
        planCell.textLabel.text = sportStr;
        return planCell;
    }
    return nil;
}

- (void)reloadWithUserInfo:(UserModel *)userInfo
{
    self.userInfo = userInfo;
    
    [self loadSportHobby];
    [self loadSportHistory];
    
    [self.centerTableView reloadData];
}

- (void)loadSportHistory
{
    //todo
    if (self.currentPage == 0) {
        self.sportHistoryArray = [NSMutableArray array];
    }
    
    @weakify(self)
    [SportPlanNet getHistoryWithUserId:self.userInfo.userId pageNumber:self.currentPage + 1 pageSize:10 successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self)
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSDictionary *dict = [responseObject objectForKey:@"data"];
            
            self.currentPage = [[dict objectForKey:@"pageNumber"] integerValue];
            self.totalPage = [[dict objectForKey:@"totalPage"] integerValue];
            
            [self.sportHistoryArray addObjectsFromArray:[dict objectForKey:@"list"]];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.currentPage == self.totalPage) {
                    ((NDRefreshLoadMoreContentView *)(self.centerTableView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNoMore;
                } else {
                    ((NDRefreshLoadMoreContentView *)(self.centerTableView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNormal;
                }
                
                [self.centerTableView reloadData];
//                NSIndexSet *set = [NSIndexSet indexSetWithIndex:1];
//                [self.centerTableView reloadSections:set withRowAnimation:UITableViewRowAnimationNone];
                
                [self.centerTableView nd_endLoadMore];
            });
            
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)loadSportHobby
{
    @weakify(self)
    [SportPlanNet getHobbyListWithUserId:self.userInfo.userId successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self)
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSArray *hobbyArray = [responseObject objectForKey:@"data"];
            
            self.userInfo.hobby_sport = [NSMutableArray array];
            for (NSString *hobby in hobbyArray) {
                [self.userInfo.hobby_sport addObject:[self convertSportNameToIcon:hobby]];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.centerTableView reloadData];
            });
            
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (NSString *)convertSportNameToIcon:(NSString *)sportName
{
    if ([sportName isEqualToString:@"游泳"]) {
        return @"swimming_icon_normal";
    } else if ([sportName isEqualToString:@"跑步"]) {
        return @"running_icon_normal";
    } else if ([sportName isEqualToString:@"篮球"]) {
        return @"basketball_icon_normal";
    } else if ([sportName isEqualToString:@"足球"]) {
        return @"football_icon_normal";
    } else if ([sportName isEqualToString:@"台球"]) {
        return @"billiards_icon_normal";
    } else if ([sportName isEqualToString:@"网球"]) {
        return @"tennis_icon_normal";
    } else {
        return @"table_icon_normal";
    }
}

@end
